// 管理用户数据相关
import { loginAPI } from "@/api/user";
import { defineStore } from "pinia";
import { ref } from "vue";
import { useCartStore } from "./cartStore";
import { margeCartAPI } from "@/api/cart";
export const useUserStore = defineStore('user', () => {
  const cartStore = useCartStore()
  // const cartStore = useCartStore()
  /**
   * 1.定义管理用户数据的state 
   * 2.定义获取接口数据的action函数
   * 3.以对象的格式把state和action return**/
  const userInfo = ref({})
  const getUserInfo = async ({ account, password }) => {
    const res = await loginAPI({ account, password })
    userInfo.value = res.result
    await margeCartAPI(cartStore.cartList.map(item => {// 合并购物车
      return {
        skuId: item.skuId,
        selected: item.selected,
        count: item.count
      }
    }))
    cartStore.updateNewList()
  }

  // 退出时清空用户信息
  const clearUserInfo = () => {
    userInfo.value = {}
    cartStore.clearCart()//清除购物车列表
  }

  return {
    userInfo,
    getUserInfo,
    clearUserInfo
  }
}, {
  persist: true,
})